//Copyright (c) 2017. 章钦豪. All rights reserved.
package com.yhh.zhongdian.view.activity;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.yhh.basemvplib.impl.IPresenter;
import com.yhh.zhongdian.DbHelper;
import com.yhh.zhongdian.MyApplication;
import com.yhh.zhongdian.R;
import com.yhh.zhongdian.base.MBaseActivity;
import com.yhh.zhongdian.constant.WelcomeTxtConstants;
import com.yhh.zhongdian.help.permission.Permissions;
import com.yhh.zhongdian.help.permission.PermissionsCompat;
import com.yhh.zhongdian.presenter.ReadBookPresenter;
import com.yhh.zhongdian.utils.theme.ThemeStore;

import butterknife.BindView;
import butterknife.ButterKnife;
import kotlin.Unit;

public class WelcomeActivity extends MBaseActivity { // implements UnionSplashAdListener {

//    private UnionSplashAD splashAD;
//    private boolean canJump = false;

    @BindView(R.id.splash_holder)
    ImageView ivBg;

    @BindView(R.id.tv_slogan)
    TextView tvSlogan;

    private volatile int phonePermisson = -1;

    @Override
    protected IPresenter initInjector() {
        return null;
    }

    /**
     * 首次安装，五天内不展示广告
     *
     * @return
     */
    private boolean canShowAd() {
        long now = System.currentTimeMillis();
        long installTime = preferences.getLong("firstStart", now);

        int timeInterval = MyApplication.getConfigPreferences().getInt("show_ad_interval_time", 5);
        Log.d(TAG, "interval: " + timeInterval + " install: " + installTime + " now: " + now);
        if (now - installTime >= 86400_000 * timeInterval) {
            return true;
        }
        return false;
    }

    @Override
    protected void onCreateActivity() {
        // 避免从桌面启动程序后，会重新实例化入口类的activity
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        setContentView(R.layout.activity_welcome);
        hideSystemNavigationBar();
        AsyncTask.execute(DbHelper::getDaoSession);
        ButterKnife.bind(this);
        tvSlogan.setText(WelcomeTxtConstants.randJoke());
        ivBg.setColorFilter(ThemeStore.accentColor(this));


        // 权限提示
        checkPermission();
        if (phonePermisson == 1) {
            // 拥有权限时的逻辑
            animatorIn();

//            FrameLayout contentView = this.findViewById(R.id.splash_container);
//            splashAD = new UnionSplashAD(this, "96AgXcYA0XN5woOBW0", "A0402361121", this, 0);
//            splashAD.fetchAndShowIn(contentView);
        } else if (phonePermisson == 0) {
            // 申请权限被拒绝
            Log.d(TAG, "申请权限被拒绝了!!!");
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", getPackageName(), null);
            intent.setData(uri);
            startActivity(intent);
        } else {
            Log.d(TAG, "初始化逻辑!!!");
        }
    }

    /**
     * 权限检查
     */
    private void checkPermission() {
        int state = getContext().checkCallingOrSelfPermission(Permissions.READ_PHONE_STATE);
        Log.d(TAG, "check permission >>" + state);
        if (PackageManager.PERMISSION_GRANTED != getContext().checkCallingOrSelfPermission(Permissions.READ_PHONE_STATE)) {
            new PermissionsCompat.Builder(this)
                    .addPermissions(Permissions.READ_PHONE_STATE)
                    .rationale("终点看书需要获取读取手机状态权限哦")
                    .onGranted((requestCode) -> {
                        Log.d(TAG, "允许了权限申请");
                        phonePermisson = 1;
                        directIn();
                        return Unit.INSTANCE;
                    })
                    .onDenied((code, s) -> {
                        toast("缺少手机状态权限哦!");
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        Log.d(TAG, "没有权限!!!");
                        phonePermisson = 0;
                        return Unit.INSTANCE;
                    }).request();
        } else {
            phonePermisson = 1;
        }
    }

    private void startBookshelfActivity() {
        startActivityByAnim(new Intent(this, MainActivity.class), android.R.anim.fade_in, android.R.anim.fade_out);
    }

    private void startReadActivity() {
        Intent intent = new Intent(this, ReadBookActivity.class);
        intent.putExtra("openFrom", ReadBookPresenter.OPEN_FROM_APP);
        startActivity(intent);
    }

    @Override
    protected void initData() {
    }

    private void hideSystemNavigationBar() {
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
            View view = this.getWindow().getDecorView();
            view.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }


//    @Override
//    public void onAdDismissed() {
//        Log.d("unions_ads", "页面消失了");
//        directIn();
//    }
//
//    @Override
//    public void onNoAd(AdError error) {
//        final String msg = error.getErrorMsg();
//        final int code = error.getErrorCode();
//        Log.d("unions_ads", "code : " + code + "  msg : " + msg);
//
//        // 直接进入
//        animatorIn();
//    }

    private void animatorIn() {
        ValueAnimator welAnimator = ValueAnimator.ofFloat(1f, 0f).setDuration(800);
        welAnimator.setStartDelay(500);
        welAnimator.addUpdateListener(animation -> {
            float alpha = (Float) animation.getAnimatedValue();
            ivBg.setAlpha(alpha);
        });
        welAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                if (preferences.getBoolean(getString(R.string.pk_default_read), false)) {
                    // 直接进入阅读界面
                    startReadActivity();
                } else {
                    // 进入书架界面
                    startBookshelfActivity();
                }
                finish();
            }

            @Override
            public void onAnimationEnd(Animator animation) {

            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        welAnimator.start();
    }


    private void directIn() {
        if (preferences.getBoolean(getString(R.string.pk_default_read), false)) {
            // 直接进入阅读界面
            startReadActivity();
        } else {
            // 进入书架界面
            startBookshelfActivity();
        }
        finish();
    }
//
//    @Override
//    public void onAdPresent() {
//        Log.d("unions_ads", "展现了");
//    }
//
//    @Override
//    public void onAdClicked() {
//        Log.d("unions_ads", "点击了页面内容");
//        // 点击广告之后，直接进入
//        directIn();
//    }
//
//    @Override
//    protected void onResume() {
//        super.onResume();
//        //此步骤主要是处理点击广告之后，退出当前的开屏页面，开发者可以根据自己的需求自己处理，不一定按照此方式处理
//        if (phonePermisson == 1 && canJump) {
//            // 点击广告之后，平滑的进入主页
//            animatorIn();
//            return;
//        }
//
//        checkPermission();
//    }
//
//    @Override
//    protected void onPause() {
//        super.onPause();
//        canJump = true;
//    }

}